package com.hitqz.robot.driver.zmq.protocol.component;


import com.hitqz.robot.driver.util.WheelCacheUtil;
import com.hitqz.robot.driver.util.WheelToolkit;
import com.hitqz.robot.driver.zmq.protocol.message.ProtocolMessage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Objects;


/**
 * zmq数据处理类-- 接收到数据通知
 */
@Slf4j
@Component
public class ReceiveHandler implements ZMQMessageHandlerServer {

    private static final HashSet<String> banSet = new HashSet<String>();

    @SneakyThrows
    @Override
    public void receive(ProtocolMessage protocolMessage) {
        String robotSn = protocolMessage.getAddress();
        if (!Objects.equals(robotSn, WheelToolkit.serialNumber)) {
            if (banSet.add(robotSn)) {
                log.warn("[wheel][zmq] error robotSn:{},abandon messages", robotSn);
            }
            return;
        }
        String[] split = protocolMessage.getType().split("\\.");
        String type = split[1];
        try {
            //fixme 现在是写死的
            Class<?> handlerClass = Class.forName("com.hitqz.robot.driver.zmq.protocol.handler." + type + "Handler");
            Method method = handlerClass.getDeclaredMethod("handlerMsg", String.class, byte[].class);
            method.invoke(handlerClass.newInstance(), robotSn, protocolMessage.getData());
        } catch (Exception e) {
            log.error("【ZMQ】数据类型:{},处理错误:{}", type, e.getMessage());
        }
        // 心跳时间戳
        WheelCacheUtil.put(WheelCacheUtil.KEY_HEART_BEAT, System.currentTimeMillis());
    }

}
